<?php
namespace app\home\controller;
use think\Request;
use think\Db;
use think\File;
use think\Session;
use think\Cookie;
use think\Controller;
use think\Config;
use Qcloud\cos\Api;

class Common extends Controller
{
	public function _initialize()
    {
		if(!session('id')){
          // $this->error('您尚未登录系统',url('login/index'));
          $this->redirect(\think\Request::instance()->root().'/home/Login/index');
        }
        $this->assign('title', '共享设备管理系统');
        $this->assign('v_role_id', session('role'));
	}

	public function lang()
    {
        switch ($_GET['lang']) {
            case 'cn':
                cookie('think_var', 'zh-cn');
                break;
            case 'en':
                cookie('think_var', 'en-us');
                break;
            //其它语言
        }
    }

    /**
     * 获取登录用户信息
     */
    public function getLoginUserInfo()
    {
	    $id = session('id');
	    $role = session('role');


        if(!empty($id)){
            switch ($role) {
                case 1: // 代理商
                case 2: // 地推
                    $data = Db::name('agent')->where(['id' => $id])->find();
                    if (empty($data)) {
                        return json(['code' => -1004, 'msg' => lang('用户不存在')]);
                    }
                    break;
                case 3: // 商户
                    $data = Db::name('seller')->where(['id' => $id])->find();
                    break;
            }
        }

        $data['session_role'] = $role;
        $data['session_id'] = $id;
        return $data;
    }

    /**
     * 上传图片
     *
     * @return \think\response\Json
     * @throws \Exception
     */
    public function uploadImage()
    {
        $file = Request::instance()->file('image');

        if ( ! $file instanceof File) {
            $this->exit_msg_callback('backFunc', '非法上传');
        }
        if ( !$file->validate(['size'=>1000*200,'ext'=>'jpg,png,gif'])->check() ) {
            $this->exit_msg_callback('backFunc', $file->getError());
        }
        //$info = FileManager::save($file);
        $info=$file->move(ROOT_PATH . 'public' . DS . 'uploads');
        $file = $info->getSaveName();
        if($file){
            $cosApi = new Api(config('Qcloud'));
            $bucket = config('Qcloud.bucket');
            $src = ROOT_PATH . 'public/uploads/'.$file;
            $dst = 'seller/picture/'. $file;
            $ret = $cosApi->upload($bucket, $src, $dst);
            $res['url'] = config('qconlineview') . '/' . $dst;
            if($ret['code']==0){
                $path = $ret['data']['resource_path'];  //获取资源文件路径（包含了APPID和bucketname）
                $len = strlen($bucket);  //计算bucketname长度
                $start = strpos($path,$bucket);   //计算bucketname第一次出现的问题
                $start +=$len;
                $newpath = substr($path,$start);  //截取路径
                unlink($src);  //删除服务器上面的资源文件
                $res['code'] = '1';
                $res['picture'] = $newpath;  //资源文件路径（需要前面添加上域名地址才可以使用）
//                $res['url'] = $ret['data']['access_url'];   //资源文件URL
                $res['url'] = config('qconlineview') . '/' . $dst;
                // $data['index_img'] = $res['picture'];

                return json($res);
            }

        }

        $this->exit_msg_callback('backFunc', '上传失败！');
    }

    /**
     * from 表单提交回调
     *
     * @param string $callback
     * @param $msg
     * @param int $res
     * @param bool $exit_flag
     */
    function exit_msg_callback($callback = 'callback', $msg, $res = 0, $exit_flag = true) {
        $res = array(
            'res' => $res,
            'msg' => $msg
        );
        $str = "<script type='text/javascript'>top.".htmlspecialchars($callback)."(".json_encode($res).");</script>";

        if($exit_flag) {
            exit($str);
        } else{
            echo $str;
        }
    }
}	



